#include "UIReceiver.h"
#include "mmcogtestmsg.h"
#include "TestInitialResult.pb.h"
#include "PainterRefreshParam.pb.h"
#include "DetailRefreshParam.pb.h"

UIReceiver* UIReceiver::m_pInstance = NULL;

UIReceiver::UIReceiver()
{
	RegisterCallback(UI_RECEIVER, LIB_UI_MSG_TEST_INITIAL_RESULT, std::bind(&UIReceiver::OnTestInitialResult, this, std::placeholders::_1));
	RegisterCallback(UI_RECEIVER, LIB_UI_MSG_PAINTER_REFRESH, std::bind(&UIReceiver::OnPainterRefreshParam, this, std::placeholders::_1));
	RegisterCallback(UI_RECEIVER, LIB_UI_MSG_DETAIL_REFRESH, std::bind(&UIReceiver::OnDetailRefreshParam, this, std::placeholders::_1));
}


UIReceiver::~UIReceiver()
{
}

UIReceiver* UIReceiver::GetInstance()
{
	if (m_pInstance == NULL) {
		m_pInstance = new UIReceiver;
	}
	return m_pInstance;
}

void UIReceiver::Destroy()
{
	if (m_pInstance == NULL) {
		return;
	}
	delete m_pInstance;
	m_pInstance = NULL;
}

void UIReceiver::OnTestInitialResult(void* ptr)
{
	TestInitialResult* result = static_cast<TestInitialResult*>(ptr);
	QVector<QString> tests;
	for (int i = 0; i < result->item_size(); ++i) {
		tests.push_back(result->item(i).test_name().c_str());
	}
	emit QTestInitialResult(tests);
}

void UIReceiver::OnPainterRefreshParam(void* ptr)
{
	PainterRefreshParam* param = static_cast<PainterRefreshParam*>(ptr);
	QVector<BDShape*> shapes;
	for (int i = 0; i < param->shape_size(); ++i) {
		switch (param->shape(i).type())
		{ 
		case PainterRefreshParam_Shape_ShapeType_SHAPE_CIRCLE:
			shapes.push_back(new BDCircle(BDPoint(param->shape(i).circle().x(), param->shape(i).circle().y()),
								param->shape(i).circle().r(),
								static_cast<BDShape::Color>(param->shape(i).circle().fill_color())));
			break;
		case PainterRefreshParam_Shape_ShapeType_SHAPE_TEXT:
			shapes.push_back(new BDString(BDPoint(param->shape(i).text().x(), param->shape(i).text().y()),
									param->shape(i).text().text().c_str()));
			break;
		case PainterRefreshParam_Shape_ShapeType_SHAPE_IMAGE:
		{
			char path[100];
			sprintf(path, ":/img/%s/%d/%d.png", param->shape(i).image().test_name().c_str(), param->shape(i).image().example() + 1, param->shape(i).image().id() + 1);
			qDebug(path);
			shapes.push_back(new BDImage(path,
				param->shape(i).image().size(),
				BDPoint(param->shape(i).image().x(), param->shape(i).image().y())));
			break;
		}
		}
	}
	emit QPainterRefreshParam(shapes);
}

void UIReceiver::OnDetailRefreshParam(void* ptr)
{
	DetailRefreshParam* param = static_cast<DetailRefreshParam*>(ptr);
	QMap<QString, QString> details;
	for (int i = 0; i < param->item_size(); ++i) {
		details[param->item(i).key().c_str()] = param->item(i).value().c_str();
	}
	emit QDetailRefreshParam(details);
}